package com.unisci.android;

import java.util.ArrayList;
import java.util.Date;

import com.bigkoo.pickerview.TimePickerView;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;

import com.unisci.android.dialog.TimeDialog;
import com.unisci.android.dialog.TimeDialog.onTimePickedListener;
import com.unisci.android.utils.HttpCmd;
import com.unisci.android.utils.ProjectItem;
import com.unisci.android.utils.ToastShow;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class WorkActivity extends Activity implements OnClickListener,
		onTimePickedListener {

	private static final String TAG = "PCR";
	private final boolean DEBUG = true;

	private TextView mTitleTextView;

	private static final int STAGE_ENUM_TEMP = 0;
	private static final int STAGE_ENUM_TIME = 1;
	private static final int STAGE_ENUM_TEMP_DOWN = 2;
	private static final int STAGE_ENUM_LOOP_STAGE = 3;
	private static final int STAGE_ENUM_LOOP = 4;
	private static final int STAGE_END = 5;

	private TextView[] stage1;
	private TextView[] stage2;
	private TextView[] stage3;
	private TextView[] stage4;
	private TextView[] stage5;

	private TimeDialog mTimeDialog;

	private ToastShow mToast;

	private ProjectItem mProjectItem = null;

	private LineChartView mChartView;
	private LineChartData mChartData;
	private int numberOfLines = 1;
	private int maxNumberOfLines = 4;
	private int numberOfPoints = 12;

	private boolean hasAxes = true;
	private boolean hasAxesNames = true;
	private boolean hasLines = true;
	private boolean hasPoints = true;
	private ValueShape shape = ValueShape.CIRCLE;
	private boolean isFilled = false;
	private boolean hasLabels = false;
	private boolean isCubic = true;
	private boolean hasLabelForSelected = false;
	private boolean pointsHaveDifferentColor;

	private String mName;

	// for debug
	private Button mStartButton;
	private Button mDebugButton;

	// get
	private final String PATH_GET_VERSION = "http://10.10.100.254:8899/cgi/version_get.cgi?type=json";
	private final String PATH_GET_RUNCONF = "http://10.10.100.254:8899/cgi/runconf_get.cgi?type=json";
	private final String PATH_GET_STATUS = "http://10.10.100.254:8899/cgi/status_get.cgi?type=json";
	// post
	private final String PATH_SET_CONF = "http://10.10.100.254:8899/cgi/conf_set.cgi";
	private final String PATH_SET_MODE = "http://10.10.100.254:8899/cgi/mode_set.cgi";
	private final String PATH_RESET = "http://10.10.100.254:8899/cgi/reset.cgi";

	private TimePickerView mTimePickerView;

	private Handler mCommHandler = new Handler() {
		public void handleMessage(Message msg) {
			JSONObject json = (JSONObject) msg.obj;
			String toastString = "";
			// mDebugTextView.setText(json.toString());
			try {
				switch (msg.what) {
				case HttpCmd.PCR_CMD_GET_VERSION:
					if (msg.arg1 == HttpCmd.PCR_CMD_OK) {
						try {
							mToast.toastShow("version: " + json.getInt("SWV")
									+ "SW" + json.get("SWStr") + "MCU"
									+ json.get("MCUV") + ""
									+ json.get("MCUStr"));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// execTask(new HttpCmd(HttpCmd.DIRECTION_INPUT,
						// HttpCmd.PCR_CMD_GET_RUNCONF, STATUS_PATH_JSON));
					} else {
						mToast.toastShow("Get version failed");
					}
					break;
				case HttpCmd.PCR_CMD_GET_STATUS:
					if (msg.arg1 == HttpCmd.PCR_CMD_OK) {
						toastString = "count = " + json.getInt("count");
						toastString += "\ntid = " + json.getInt("tid");
						toastString += "\ncontinue = "
								+ json.getBoolean("continue");
						toastString += "\nct = " + json.getString("ct");

						JSONArray ctArray = json.getJSONArray("ct");
						JSONObject ct = ctArray.getJSONObject(0);

						double temper = ct.getDouble("temper");
						int time = ct.getInt("elapsed");
						Log.d(TAG, "temper = " + temper);
						// draw point
						mTemPointValues
								.add(new PointValue(time, (float) temper));
						loadSetting();

						mToast.toastShow(toastString);
					} else {
						mToast.toastShow("Get status failed");
					}
					break;
				case HttpCmd.PCR_CMD_GET_RUNCONF:
					if (msg.arg1 == HttpCmd.PCR_CMD_OK) {
						toastString = "cf = " + json.getString("cf");
						mToast.toastShow(toastString);
					} else {
						mToast.toastShow("Get config failed");
					}
					break;
				case HttpCmd.PCR_CMD_SET_MODE:
					if (msg.arg1 == HttpCmd.PCR_CMD_OK) {
						mToast.toastShow("set mode done!");
					} else {
						mToast.toastShow("set mode failed");
					}
					break;

				case HttpCmd.PCR_CMD_SET_CONFIG:
					if (msg.arg1 == HttpCmd.PCR_CMD_OK) {
						mToast.toastShow("set mode done!");
					} else {
						mToast.toastShow("set mode failed");
					}
					break;
				case HttpCmd.PCR_CMD_RESET:
					if (msg.arg1 == HttpCmd.PCR_CMD_OK) {
						mToast.toastShow("reset done!");
					} else {
						mToast.toastShow("reset failed");
					}
					break;
				case HttpCmd.PCR_CMD_UNKNOW:
					mToast.toastShow("Get unknow cmd");
					break;
				default:
					break;
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_work);
		Intent intent = getIntent();
		String name = intent.getStringExtra("name");
		mName = name;
		initViews(name);
		List<ProjectItem> items = UnisciApplication.getInstance().getDb()
				.getRecords("zhangjie");
		for (int i = 0; i < items.size(); i++) {
			if (items.get(i).getName().equals(name)) {
				mProjectItem = items.get(i);
				break;
			}
		}

		if (mProjectItem != null) {
			loadData();
		} else {
			mToast.toastShow("NULL DATA");
		}
		if (DEBUG) {
			loadSetting();
			mChartView.setLineChartData(mChartData);
			mChartView.setViewportCalculationEnabled(true);
			resetViewport(120, mChartData.getLines().get(0).getValues().size());
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void loadData() {
		stage1[STAGE_ENUM_TEMP].setText("温度: " + mProjectItem.getTemp(0) + "℃");
		stage1[STAGE_ENUM_TIME].setText("时间: " + mProjectItem.getTime(0) + "秒");
		stage2[STAGE_ENUM_TEMP].setText("温度: " + mProjectItem.getTemp(1) + "℃");
		stage2[STAGE_ENUM_TIME].setText("时间: " + mProjectItem.getTime(1) + "秒");
		stage3[STAGE_ENUM_TEMP].setText("温度: " + mProjectItem.getTemp(2) + "℃");
		stage3[STAGE_ENUM_TIME].setText("时间: " + mProjectItem.getTime(2) + "秒");
		stage3[STAGE_ENUM_TEMP_DOWN].setText("循环递减: "
				+ mProjectItem.getTempDown(2));
		stage4[STAGE_ENUM_TEMP].setText("温度: " + mProjectItem.getTemp(3) + "℃");
		stage4[STAGE_ENUM_TIME].setText("时间: " + mProjectItem.getTime(3) + "秒");
		stage4[STAGE_ENUM_LOOP_STAGE].setText("循环跳转: "
				+ mProjectItem.getLoopStage(3));
		stage4[STAGE_ENUM_LOOP].setText("循环次数: " + mProjectItem.getLoop(3));
		stage5[STAGE_ENUM_TEMP].setText("温度: " + mProjectItem.getTemp(4) + "℃");

		String time = "时间: ";
		int minite = mProjectItem.getTime(4) / 60;
		int second = mProjectItem.getTime(4) % 60;
		if (minite != 0) {
			time += String.format("%d分", minite);
		}
		time += String.format("%d秒", second);
		stage5[STAGE_ENUM_TIME].setText(time);
	}

	private void initViews(String title) {
		mToast = new ToastShow(this);
		stage1 = new TextView[STAGE_END];
		stage2 = new TextView[STAGE_END];
		stage3 = new TextView[STAGE_END];
		stage4 = new TextView[STAGE_END];
		stage5 = new TextView[STAGE_END];
		stage1[STAGE_ENUM_TEMP] = (TextView) findViewById(R.id.stage1_temp);
		stage1[STAGE_ENUM_TIME] = (TextView) findViewById(R.id.stage1_time);
		stage2[STAGE_ENUM_TEMP] = (TextView) findViewById(R.id.stage2_temp);
		stage2[STAGE_ENUM_TIME] = (TextView) findViewById(R.id.stage2_time);
		stage3[STAGE_ENUM_TEMP] = (TextView) findViewById(R.id.stage3_temp);
		stage3[STAGE_ENUM_TIME] = (TextView) findViewById(R.id.stage3_time);
		stage3[STAGE_ENUM_TEMP_DOWN] = (TextView) findViewById(R.id.stage3_temp_down);
		stage4[STAGE_ENUM_TEMP] = (TextView) findViewById(R.id.stage4_temp);
		stage4[STAGE_ENUM_TIME] = (TextView) findViewById(R.id.stage4_time);
		stage4[STAGE_ENUM_LOOP_STAGE] = (TextView) findViewById(R.id.stage4_loop_stage);
		stage4[STAGE_ENUM_LOOP] = (TextView) findViewById(R.id.stage4_loop);
		stage5[STAGE_ENUM_TEMP] = (TextView) findViewById(R.id.stage5_temp);
		stage5[STAGE_ENUM_TIME] = (TextView) findViewById(R.id.stage5_time);

		for (int i = 0; i < STAGE_END; i++) {
			if (stage1[i] != null) {
				stage1[i].setTag(i);
				if (i == STAGE_ENUM_TIME) {
					stage1[i].setOnClickListener(new TextOnClickListener());
				}
			}
		}
		for (int i = 0; i < STAGE_END; i++) {
			if (stage2[i] != null) {
				stage2[i].setTag(i + STAGE_END);
				if (i == STAGE_ENUM_TIME) {
					stage2[i].setOnClickListener(new TextOnClickListener());
				}
			}
		}
		for (int i = 0; i < STAGE_END; i++) {
			if (stage3[i] != null) {
				stage3[i].setTag(i + STAGE_END * 2);
				if (i == STAGE_ENUM_TIME) {
					stage3[i].setOnClickListener(new TextOnClickListener());
				}
			}
		}
		for (int i = 0; i < STAGE_END; i++) {
			if (stage4[i] != null) {
				stage4[i].setTag(i + STAGE_END * 3);
				if (i == STAGE_ENUM_TIME) {
					stage4[i].setOnClickListener(new TextOnClickListener());
				}
			}
		}
		for (int i = 0; i < STAGE_END; i++) {
			if (stage5[i] != null) {
				stage5[i].setTag(i + STAGE_END * 4);
				if (i == STAGE_ENUM_TIME) {
					stage5[i].setOnClickListener(new TextOnClickListener());
				}
			}
		}

		mStartButton = (Button) findViewById(R.id.btn_start);
		mStartButton.setOnClickListener(this);
		mDebugButton = (Button) findViewById(R.id.btn_debug);
		mDebugButton.setOnClickListener(this);

		mTitleTextView = (TextView) findViewById(R.id.tv_title);
		mTitleTextView.setText(title);

		mTimeDialog = new TimeDialog(this);
		mTimeDialog.setOnTimePickedListener(this);
		// load chart
		mChartView = (LineChartView) findViewById(R.id.chart);
		// mChartView.setOnValueTouchListener(new ValueTouchListener());

		mTimePickerView = new TimePickerView(this, TimePickerView.Type.ALL);
		mTimePickerView.setTime(new Date());
		mTimePickerView.setCancelable(true);
		mTimePickerView
				.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

					@Override
					public void onTimeSelect(Date date) {
					}
				});
	}

	private void resetViewport(int top, int right) {
		// Reset viewport height range to (0,100)
		final Viewport v = new Viewport(mChartView.getMaximumViewport());
		v.bottom = 0;
		v.top = top;
		v.left = 0;
		v.right = right;
		mChartView.setMaximumViewport(v);
		mChartView.setCurrentViewport(v);
	}

	private class TextOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int tag = Integer.valueOf((Integer) v.getTag());
			// mToast.toastShow("tag = " + tag);
//			mTimeDialog.setTag(tag);
//			mTimeDialog.show();
			mTimePickerView.show();
		}
	}

	private List<PointValue> mTemPointValues = new ArrayList<PointValue>();

	private void loadSetting() {
		List<Line> lines = new ArrayList<Line>();
		List<PointValue> values = new ArrayList<PointValue>();

		int index = 0;

		int climb1 = (int) (mProjectItem.getTemp(0) / 3);
		int climb2 = (int) ((mProjectItem.getTemp(1) - mProjectItem.getTemp(0)) / 3);
		int climb3 = (int) ((mProjectItem.getTemp(2) - mProjectItem.getTemp(1)) / 3);
		int climb4 = (int) ((mProjectItem.getTemp(3) - mProjectItem.getTemp(2)) / 3);
		int climb5 = (int) ((mProjectItem.getTemp(4) - mProjectItem.getTemp(3)) / 3);

		Log.d(TAG, "" + climb1 + ", " + climb2 + ", " + climb3 + ", " + climb4);

		numberOfPoints = mProjectItem.getTime(0) + mProjectItem.getTime(1)
				+ mProjectItem.getTime(2) + mProjectItem.getTime(3) + climb1
				+ climb2 + climb3 + climb4 + climb5;

		for (int i = 0; i < climb1; i++) {
			values.add(new PointValue(index, i * 3));
			index = index + 1;
		}

		for (int i = 0; i < mProjectItem.getTime(0); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(0)));
			index = index + 1;
		}

		for (int i = 0; i < (0 - climb2); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(0) - i * 3));
			index = index + 1;
		}

		for (int i = 0; i < mProjectItem.getTime(1); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(1)));
			index = index + 1;
		}

		for (int i = 0; i < (0 - climb3); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(1) - i * 3));
			index = index + 1;
		}

		for (int i = 0; i < mProjectItem.getTime(2); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(2)));
			index = index + 1;
		}

		for (int i = 0; i < climb4; i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(2) + i * 3));
			index = index + 1;
		}

		for (int i = 0; i < mProjectItem.getTime(3); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(3)));
			index = index + 1;
		}

		for (int i = 0; i < (0 - climb5); i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(3) - i * 3));
			index = index + 1;
		}

		for (int i = 0; i < numberOfPoints; i++) {
			values.add(new PointValue(index, mProjectItem.getTemp(4)));
			index = index + 1;
		}

		Line line = new Line(values);
		line.setColor(ChartUtils.COLORS[2]);
		line.setShape(shape);
		line.setCubic(isCubic);
		line.setFilled(isFilled);
		line.setHasLabels(hasLabels);
		line.setHasLabelsOnlyForSelected(hasLabelForSelected);
		line.setHasLines(hasLines);
		line.setHasPoints(hasPoints);
		line.setPointRadius(0);
		line.setStrokeWidth(4);

		Line line2 = new Line(mTemPointValues);
		line2.setColor(ChartUtils.COLORS[1]);
		line2.setShape(shape);
		line2.setCubic(isCubic);
		line2.setFilled(isFilled);
		line2.setHasLabels(hasLabels);
		line2.setHasLabelsOnlyForSelected(hasLabelForSelected);
		line2.setHasLines(hasLines);
		line2.setHasPoints(hasPoints);
		line2.setPointRadius(0);
		line2.setStrokeWidth(3);

		lines.add(line);
		lines.add(line2);

		mChartData = new LineChartData(lines);

		if (hasAxes) {
			Axis axisX = new Axis();
			axisX.setTextColor(ChartUtils.COLOR_BLUE);
			Axis axisY = new Axis().setHasLines(true);
			axisY.setTextColor(ChartUtils.COLOR_BLUE);
			if (hasAxesNames) {
				axisX.setName("时间/秒");
				axisY.setName("温度/℃");
			}
			mChartData.setAxisXBottom(axisX);
			mChartData.setAxisYLeft(axisY);

		} else {
			mChartData.setAxisXBottom(null);
			mChartData.setAxisYLeft(null);
		}

		mChartData.setBaseValue(Float.NEGATIVE_INFINITY);
		mChartView.setLineChartData(mChartData);
	}

	private void execTask(HttpCmd cmd) {
		new CommAsyncTask(mCommHandler).execute(cmd);
	}

	private void reset() {
		JSONObject param = new JSONObject();
		try {
			param.put("PRIVKEY", "YouKe1PRI2VKE0Y");
			execTask(new HttpCmd(HttpCmd.DIRECTION_OUTPUT,
					HttpCmd.PCR_CMD_SET_CONFIG, PATH_RESET, param));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setMode(String mode) {
		JSONObject param = new JSONObject();
		try {
			param.put("mode", mode);
			execTask(new HttpCmd(HttpCmd.DIRECTION_OUTPUT,
					HttpCmd.PCR_CMD_SET_MODE, PATH_SET_MODE, param));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void sendConfig() {
		JSONObject param = new JSONObject();
		JSONArray array = new JSONArray();
		try {
			param.put("flag", 0x00);
			param.put("temper_heat_top", 100);

			JSONObject item1 = new JSONObject();
			JSONObject item2 = new JSONObject();
			JSONObject item3 = new JSONObject();
			JSONObject item4 = new JSONObject();
			JSONObject item5 = new JSONObject();
			// 1
			item1.put("temper", mProjectItem.getTemp(0));
			item1.put("time", mProjectItem.getTime(0));
			// 2
			item2.put("temper", mProjectItem.getTemp(1));
			item2.put("time", mProjectItem.getTime(1));
			// 3
			item3.put("temper", mProjectItem.getTemp(2));
			item3.put("time", mProjectItem.getTime(2));
			item3.put("temper_down", mProjectItem.getTempDown(2));
			// 4
			item4.put("temper", mProjectItem.getTemp(3));
			item4.put("time", mProjectItem.getTime(3));
			item4.put("loop_stage", mProjectItem.getLoopStage(3));
			item4.put("loop", mProjectItem.getLoop(3));
			// 5
			item5.put("temper", mProjectItem.getTemp(4));
			item5.put("time", mProjectItem.getTime(4));

			array.put(0, item1);
			array.put(1, item2);
			array.put(2, item3);
			array.put(3, item4);
			array.put(4, item5);
			param.put("cf", array);

			execTask(new HttpCmd(HttpCmd.DIRECTION_OUTPUT,
					HttpCmd.PCR_CMD_SET_CONFIG, PATH_SET_CONF, param));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.btn_start:
			sendConfig();
			// execTask(new HttpCmd(HttpCmd.DIRECTION_INPUT,
			// HttpCmd.PCR_CMD_GET_VERSION, PATH_GET_VERSION));
			break;
		case R.id.btn_debug:

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					for (int i = 0; i < 200; i++) {
						try {
							execTask(new HttpCmd(HttpCmd.DIRECTION_INPUT,
									HttpCmd.PCR_CMD_GET_STATUS, PATH_GET_STATUS));
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}).start();

			break;
		default:
			break;
		}
	}

	@Override
	public void onTimePicked(int tag, int min, int sec) {
		// TODO Auto-generated method stub
		String time = "时间: ";
		if (min != 0) {
			time += String.format("%d分", min);
		}
		time += String.format("%d秒", sec);
		if (tag / STAGE_END == 0) {
			stage1[STAGE_ENUM_TIME].setText(time);
			mProjectItem.setTime(0, 60 * min + sec);
		} else if (tag / STAGE_END == 1) {
			stage2[STAGE_ENUM_TIME].setText(time);
			mProjectItem.setTime(1, 60 * min + sec);
		} else if (tag / STAGE_END == 2) {
			stage3[STAGE_ENUM_TIME].setText(time);
			mProjectItem.setTime(2, 60 * min + sec);
		} else if (tag / STAGE_END == 3) {
			stage4[STAGE_ENUM_TIME].setText(time);
			mProjectItem.setTime(3, 60 * min + sec);
		} else if (tag / STAGE_END == 4) {
			stage5[STAGE_ENUM_TIME].setText(time);
			mProjectItem.setTime(4, 60 * min + sec);
		}
		UnisciApplication.getInstance().getDb()
				.update("zhangjie", mProjectItem, mName);
		loadSetting();
		resetViewport(120, mChartData.getLines().get(0).getValues().size());
		mToast.toastShow("right = "
				+ mChartData.getLines().get(0).getValues().size());
	}
}
